/*
 * Copyright 2012 NJUT  qixiaobo. All rights reserved.
 */
package com.snda.game.legend.velocity.tools;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.velocity.runtime.log.Log;
import org.apache.velocity.tools.config.DefaultKey;
import org.apache.velocity.tools.generic.SafeConfig;
import org.apache.velocity.tools.generic.ValueParser;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Scope;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import com.snda.game.legend.common.PropertyUtils;

/**
 * DomainTool.java
 * 
 * @author Qixiaobo-win8
 */
@DefaultKey("domain")
@Scope
@DependsOn
public class DomainTool extends SafeConfig {
	private final static String HAS_COMPRESSED = ".min";
	private static Properties context;
	protected Log LOG;
	static {
		Resource r = new ClassPathResource(
				"com/snda/props/context.properties");
		try {
			context = PropertyUtils.readFromResource(r);
		} catch (IOException e) {
			context = new Properties();
		}
	}
	public String info(String key) {
		return context.getProperty(key);
	}

	public String getCopyrightYear() {
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		return String.valueOf(c.get(Calendar.YEAR));
	}
	public String getDomain() {
		return info("domain");
	}

	public String get() {
		return getDomain();
	}
	@Override
	protected void configure(ValueParser props) {
		LOG = (Log) props.getValue("log");
	}

	public String fileSize(String size) {
		double sizeNum = Integer.parseInt(size);
		String[] list = new String[]{"B", "KB", "MB", "GB", "TB"};
		int position = 0;
		while (sizeNum >= 1024) {
			sizeNum /= 1024.0;
			position++;
		}
		return Math.round(sizeNum) + " " + list[position];
	}


	public void write(String key, String value) {
		context.setProperty(key, value);
	}
	public void write(HashMap<String, String> map) {
		for (Entry<String, String> entry : map.entrySet()) {
			write(entry.getKey(), entry.getValue());
		}
	}
	public String checkName(String name) {
		if (!name.endsWith(HAS_COMPRESSED) && !name.equals("ckeditor/ckeditor")) {
			// ckeditor 压缩后出错（压缩时将变量名替换了）
			name += HAS_COMPRESSED;
		}
		return name;
	}

    public String isNight() {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        if (hour >= 21 || hour < 9) {
            return "true";
        }
        return "false";
    }
}
